import java.io.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import app.Usuario;
import database.*;
import java.util.Properties;
import java.util.regex.Pattern;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Servlet implementation class Vencom
 */
public class Inicio extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UsuarioDAO DBuser;
	private Connection con;
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Inicio() {
		super();
		DBuser = null;
		con = null;
	}

	public void init() {
	    try {
	      /* Leyendo propiedades para la BD */
	      Properties prop = new Properties();
	      ClassLoader loader = this.getClass().getClassLoader();
	      InputStream in = loader.getResourceAsStream("database/database.properties");
	      prop.load(in);
	      in.close();
	      String drivers = prop.getProperty("jdbc.drivers");
	      if (drivers != null)
	        System.setProperty("jdbc.drivers", drivers);
	      String url = prop.getProperty("jdbc.url");
	      String user = prop.getProperty("jdbc.user");
	      String password = prop.getProperty("jdbc.password");

	      // Creando conexion
	      con = DriverManager.getConnection(url, user, password);
	      DBuser = new UsuarioDAO (con);
	    } 
	    catch (IOException e) {
	      e.printStackTrace();
	      con = null;
	    } 
	    catch (SQLException ex) {
	      ex.printStackTrace();
	      con = null;
	    }
    
	}

	public void destroy() {
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Comprueba que los nombres sean alfanumericos
	 */
	public boolean isAlphanumeric(String s) {
		String regexp = "[a-zA-Z_0-9]+";
		return Pattern.matches(regexp, s);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
						 HttpServletResponse response) throws IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, 
						  HttpServletResponse response) throws IOException {
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/home.jsp");
		
		String nom = request.getParameter("user");
		String pass = request.getParameter("password");

		nom.trim();
		pass.trim();
		
		
		if (isAlphanumeric(nom) && isAlphanumeric(pass)) {
			Usuario u = DBuser.identificarse(nom, pass);
			
			if (u != null) {
	/*			out.println("<head>\n" +
							"	<title> Vencom.Prop </title>\n" +
							"   <meta http-equiv=\"Refresh\" content=\"0; home.jsp\"> " +
							"</head>");*/
				
				HttpSession session = request.getSession();
				session.setAttribute("vuser", u);
				
				try {
					dispatcher.include(request, response);
				}
				
				catch (ServletException e) {
					e.printStackTrace();
				}
				
			} else {
				response.sendRedirect("index.jsp?error=login_error");
				/*
				out.println("<head>\n" +
						"	<title> Vencom.Prop </title>\n" +
						"   <meta http-equiv=\"Refresh\" content=\"5;url=index.jsp\"> "+ 
						"</head>");
			
				out.println("<body>\n"+
						"	<h1> Error en la introduccion de datos </h1>\n" +
						"  	<h2> Seras redirigido a la paginia inical en 5 segundos. </h2>\n" +
						"   <h2> Puedes acceder haciendo click <a href=\"index.jsp\">aqui</a></h2>" +
						"</body>");*/
			}
		} else {
			response.sendRedirect("index.jsp?error=login_error");
			/*
			out.println("<head>\n" +
					"	<title> Vencom.Prop </title>\n" +
					"   <meta http-equiv=\"Refresh\" content=\"5;url=index.jsp\"> "+ 
					"</head>");
		
			out.println("<body>\n"+
					"	<h1> Error en la introduccion de datos </h1>\n" +
					"  	<h2> Seras redirigido a la paginia inical en 5 segundos. </h2>\n" +
					"   <h2> Puedes acceder haciendo click <a href=\"index.jsp\">aqui</a></h2>" +
					"</body>");*/
		}

	}
	
	private void createDAOs() {
	    try {
	      DBuser = new UsuarioDAO(con);
	    }
	    catch (SQLException ex) {
	      ex.printStackTrace();
	      DBuser = null;
	      con = null;
	    }
	}
}
